import UserServices from '@/services/user';
import { requestSuccess } from '@/utils/tools';

const handleListData = (rawList) => {
  let list = [];
  for(let catetory in rawList){
    for(let key in rawList[catetory]){
      const data = rawList[catetory][key];
      if(global._.isObject(data)){
        data._type = catetory;
      }
      if(global._.isArray(data)){
        for(let i of data){
          i._type = catetory;
        }
      }
      list = list.concat(data);
    }
  }
  list = global._.sortBy(list, function(item) {
    return -item.created;
  });
  return list;
}

export default {

  namespace: 'user',

  state: {
    refreshing: false,
    list: [],
  },

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line
    },
  },

  effects: {
    *getList({ payload }, { call, put, select }) {  // eslint-disable-line
      const cacheName = payload.cacheName;
      const cacheList = yield select(({ user }) => user[cacheName]);
      // yield put({ type: 'save' , payload: {list: handleListData(cacheList)}});

      const result = yield call(UserServices[payload.api]);
      if(requestSuccess(result)){
        // yield put({ type: 'save' , payload: {[cacheName]: result.data}});
        yield put({ type: 'save' , payload: {list: handleListData(result.data)}});
      }
    },
  },

  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },
  },

};
